package com.lgst.ticket;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    private Spinner mDate;
    private EditText mDestination;
    private List<String> datas;
    private AlertDialog mPd;
    private String station = "1000";
    private ArrayList<TicketInfo> mTickets;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
    }

    private void initData() {
        new Thread() {
            @Override
            public void run() {
                try {
                    datas = new ArrayList<>();
                    Document document = Jsoup.connect(Net.HOST).get();
                    Element dateE = document.body().getElementById("selected1");//日期列表
                    Elements es = dateE.getAllElements();
                    for (Element e : es) {
                        datas.add(e.attr("value").trim());
                    }
                    datas.remove(0);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initView();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void initView() {
        Spinner mStation = (Spinner) findViewById(R.id.station);
        mDate = (Spinner) findViewById(R.id.date);
        mDate.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, datas));
        mDestination = (EditText) findViewById(R.id.destination);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Button mSearchBtn = (Button) findViewById(R.id.search_btn);
        mSearchBtn.setOnClickListener(this);
        mStation.setOnItemSelectedListener(this);
    }

    private boolean submit() {
        String destinationString = mDestination.getText().toString().trim();
        if (TextUtils.isEmpty(destinationString)) {
            Snackbar.make(mDate, "请填写目的地！", Snackbar.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_btn:
                if (!submit())
                    return;
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            search();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
        }
    }

    private void search() throws IOException {
        /*  selected:1000
            selected2:05:00
            selected1:2017-01-16
            Arrive:白河
            page:
            ArriveHidden:
            */
        mTickets = new ArrayList<TicketInfo>();
        Map<String, String> params = new HashMap<>();
        params.put("selected", station);
        params.put("selected2", "05:00");
        params.put("selected1", ((String) mDate.getSelectedItem()));
        params.put("Arrive", mDestination.getText().toString().trim());
        params.put("page", "");
        params.put("ArriveHidden", "");
        Element element = Jsoup.connect(Net.SEARCH).method(Connection.Method.POST).data(params).post().body();
        Elements es = element.getElementsByClass("tr4");
        for (Element e : es) {
            Elements infoEs = e.getElementsByTag("div");
            infoEs.remove(8);
            infoEs.remove(0);
            String[] infos = new String[7];
            int i = 0;
            for (Element infoE : infoEs) {
                String str = infoE.text();
                str.trim();
                if (str.isEmpty()) {
                    continue;
                }
                infos[i++] = str;
            }
            TicketInfo ticket = new TicketInfo();
            ticket.setDestination(infos[0]);
            ticket.setDate(infos[1]);
            ticket.setTime(infos[2]);
            ticket.setStation(infos[3]);
            ticket.setTicketNum(infos[4]);
            ticket.setCarType(infos[5]);
            ticket.setPrice(infos[6]);
            mTickets.add(ticket);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(MainActivity.this, SearchActivity.class).putParcelableArrayListExtra("values", mTickets));
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        switch (i) {
            case 0:
                station = "1000";
                break;
            case 1:
                station = "1002";
                break;
            case 2:
                station = "1004";
                break;
            case 3:
                station = "1003";
                break;
            case 4:
                station = "1009";
                break;
            case 5:
                station = "1005";
                break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}
